class Product < ActiveRecord::Base
  acts_as_paranoid
  has_paper_trail

  has_many :sales

  validates :validity_type, inclusion: { in: %w[forever day month] }
  validates :validity_duration, numericality: { greater_than: 0 }, if: "validity_type != 'forever'"
  validate :sale_start_less_than_end

  def validity
    case validity_type
      when 'forever'
        '一直有效'
      when 'day'
        "#{validity_duration} 天"
      when 'month'
        "#{validity_duration} 个月"
    end
  end

  def sale_duration
    if self.sale_start_at && self.sale_end_at
      "#{self.sale_start_at.strftime('%F')} ~ #{self.sale_end_at.strftime('%F')}"
    elsif self.sale_start_at
      "#{self.sale_start_at.strftime('%F')}开始"
    elsif self.sale_end_at
      "#{self.sale_end_at.strftime('%F')}结束"
    else
      '一直销售'
    end
  end

  private
  def sale_start_less_than_end
    if self.sale_start_at && self.sale_end_at
      errors.add(:base, "销售开始时间必须小于结束时间") if sale_start_at > sale_end_at
    end
  end
end
